using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class WeaponUpgradeButton : MonoBehaviour {

	Text myText;

	static WeaponUpgradeButton currentWeaponUpgradeType = null;

	void OnLevelWasLoaded(int level) {
		currentWeaponUpgradeType = null;
	}

	public string weaponTypeName = "Multi-Shot";
	int currentLevel = 0;

	public GameObject[] bulletLevels;
	GameManager gm;
	void Start() {
		gm = GameObject.FindObjectOfType<GameManager>();
	}

	int CostForLevel() {
		return (int)(50 * Mathf.Pow(2f, currentLevel));
	}

	string UpgradeName() {
		string s = weaponTypeName + " ";

		if(currentWeaponUpgradeType != this) {
			s = "<color=red>Switch to:</color> " + s;
		}
		else {
			s = "<color=green>Current:</color> " + s;
		}

		if(currentLevel >= bulletLevels.Length) {
			s += "MAXED!";
		}
		else {
			s += + (currentLevel+1) + " - " + "$" + CostForLevel();
		}


		return s;
	}

	void Update() {
		if(myText == null) {
			myText = transform.Find ("Text").GetComponent<Text>();
		}

		myText.text = UpgradeName();

		if(gm.score < CostForLevel()) {
			this.GetComponent<Image>().color = Color.grey;
		}
		else {
			this.GetComponent<Image>().color = Color.white;
		}

	}

	public void Clicked() {

		if(gm.PlayerIsDead())
			return;

		if(currentLevel >= bulletLevels.Length) {
			return;
		}

		if(gm.score < CostForLevel())
			return;


		if(currentWeaponUpgradeType != null && currentWeaponUpgradeType != this) {
			currentWeaponUpgradeType.Unclicked();
		}

		currentWeaponUpgradeType = this;

		gm.score -= CostForLevel();
		gm.SetPlayerBullet( bulletLevels[currentLevel] );
		currentLevel++;
	}

	public void Unclicked() {
		currentLevel--;
	}
}
